package com.example.student.controller;

import com.example.student.model.RtspRequest;
import com.example.student.model.StreamResponse;
import com.example.student.service.RtspService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/api/stream")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class RtspController {

    private final RtspService rtspService;

    @Value("${server.port:8080}")
    private String serverPort;

    @PostMapping("/start")
    public ResponseEntity<StreamResponse> startStream(@RequestBody RtspRequest request, HttpServletRequest servletRequest) {
        log.info("Received request to start stream: {}", request.getRtspUrl());
        String streamId = rtspService.startStream(request.getRtspUrl());

        // 构建完整的HLS URL，包含主机名和端口
        String serverAddress = getServerAddress(servletRequest);
        String hlsUrl = serverAddress + "/hls-streams/" + streamId + ".m3u8";

        log.info("Stream started. HLS URL: {}", hlsUrl);
        return ResponseEntity.ok(new StreamResponse(streamId, hlsUrl));
    }

    @PostMapping("/stop/{streamId}")
    public ResponseEntity<Void> stopStream(@PathVariable String streamId) {
        log.info("Received request to stop stream: {}", streamId);
        rtspService.stopStream(streamId);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/status/{streamId}")
    public ResponseEntity<Boolean> checkStreamStatus(@PathVariable String streamId) {
        boolean isActive = rtspService.isStreamActive(streamId);
        return ResponseEntity.ok(isActive);
    }

    /**
     * 获取服务器地址（包括协议、主机名和端口）
     */
    private String getServerAddress(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();

        // 根据请求头X-Forwarded-Host判断是否有代理
        String forwardedHost = request.getHeader("X-Forwarded-Host");
        if (forwardedHost != null && !forwardedHost.isEmpty()) {
            serverName = forwardedHost;
        }

        return scheme + "://" + serverName + ":" + serverPort;
    }
} 